<template>
  <div class="upload-box">
    <el-upload
      :class="{disabled: isDisadled}"
      :on-preview="preview"
      :file-list="fileList"
      list-type="picture-card"
      :limit="LimitCont"
      action="#"
      :on-remove="handleRemove"
      :http-request="handleUpload"
      :on-change="handleChange"
      :before-upload="handleBeforeUpload"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-dialog title="预览图片" :visible="isShowImgMax" @close="isShowImgMax = false">
      <img style="display: block; width: 100%" :src="imgUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>

import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKIDUqzykIchYBdrrb7NN8gz2rTqyrUu52nK', // 身份识别ID
  SecretKey: 'MUO3WkkW4PYUDl5B2f5KOFsHTRCj15yr' // 身份秘钥
})
export default {
  name: 'ImageUpload',
  props: {
    // eslint-disable-next-line vue/prop-name-casing
    LimitCont: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      fileList: [],
      isShowImgMax: false, // 控制显示弹层
      imgUrl: ''

    }
  },
  computed: {
    isDisadled() {
      return this.fileList.length >= this.LimitCont
    },
    isAllUploadSuccess() {
      return this.fileList.every(item => item.status === 'success')
    }
  },

  methods: {
    preview(file) {
      // 这里应该弹出一个层 层里是点击的图片地址
      this.imgUrl = file.url
      this.isShowImgMax = true
    },
    handleRemove(file, fileList) {
      this.fileList = this.fileList.filter(item => item.uid !== file.uid)
    },
    handleUpload(obj) {
      const uid = obj.file.uid
      const fileObj = this.fileList.find(item => item.uid === uid)
      fileObj.status = 'uploading'
      cos.putObject({
        Bucket: 'tangdao-1308196702', // 完整的存储桶名称
        Region: 'ap-shanghai', // 存储桶所在的地域(ap-)
        Key: parseInt(Math.random() * 9999999) + obj.file.name, // 上传到存储桶的文件名
        StorageClass: 'STANDARD', // 默认的上传模式: 标准
        Body: obj.file,

        onProgress: (progressData) => {
        //   console.log(JSON.stringify(progressData))
          // this.percent = parseInt(progressData.percent * 100)
          fileObj.percentage = parseInt(progressData.percent * 100)
        }
      }, (err, data) => {
        if (err) return
        fileObj.url = 'https://' + data.Location

        setTimeout(() => {
          fileObj.status = 'success'
        }, 500)
      })
    },
    handleChange(file, fileList) {
      // file => 操作的文件
      // fileList => 结构中的数组
      this.fileList = [...fileList]
    },
    handleBeforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
        return false
      }
      return true
    }

  }
}
</script>

<style lang='scss' scoped>
.disabled {
    ::v-deep {
 .el-upload--picture-card {
        display: none !important;

    }
 }
}
</style>
